<?php
/**
 * Created by PhpStorm.
 * User: apple
 * Date: 2018/7/22
 * Time: 下午3:38
 */
namespace PddWechat\Models\Pos\Service;
use Dai\Framework\Base\BaseException;
use Dai\Framework\Base\BaseService;
use Dai\Framework\Base\BaseSessionInfo;
use Dai\Framework\Library\RedisExt;
use PddWechat\Models\Pos\Data\PostInviteData;
use PddWechat\Models\Pos\DataObject\PostInvateDo;
use PddWechat\Models\Pos\Param\AskForPosParam;

class AskForPos extends BaseService
{
    public function __construct()
    {
        $this->postInvateData = new PostInviteData();
    }

    public function execute($basePageInfo)
    {
        /** @var AskForPosParam $params */
        $params = $basePageInfo->params;
        //校验code
        $code = $params->code;
        if ($code != RedisExt::getInstance()->get($params->phone)) {
            throw new BaseException(BaseException::SMS_CHECK_FAILED);
        }
        //判断用户是否已经申请过
        $postInvateInfo = $this->postInvateData->getApplyInfoByPhone($params->phone);
        if ($postInvateInfo != null) {
            throw new BaseException(BaseException::CAN_NOT_APPLY_TEICE);
        }
        /** @var BaseSessionInfo $sessionData */
        $sessionData = $basePageInfo->sessionInfo;
        $openid = $sessionData->openId;
        $postInvateDo = new PostInvateDo();
        if (!empty($params->invateOpenId)) {
            $postInvateDo->invateOpenId = $params->invateOpenId;
        }
        $postInvateDo->recommendOpenId = $openid;
        $postInvateDo->phone = $params->phone;
        $postInvateDo->address = $params->address;
        $postInvateDo->idcard = $params->idcard;
        $postInvateDo->name = $params->name;
        $postInvateDo->orderNum = $this->createOrderNum();
        $postInvateDo->status = 0;
        return $this->postInvateData->insert($postInvateDo);
    }

    //生成唯一订单号
    private function createOrderNum()
    {
        $danhao = date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
        return $danhao;
    }
}